package com.bigdata.hbase_mr.read;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/*
KEYIN,VALUEIN: reduce 接收并处理的数据类型, 以每个单词为一组来处理
KEYOUT,VALUEOUT: 单词出现的次数，key -> word，value -> count;
 */
public class ClazzReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
    private IntWritable result = new IntWritable();
    /**
     *
     * @param key 处理的单词
     * @param values 可以获取Iterator对象，里面可以包含多个值，每个值就是map阶段写出的value
     * @param context 通过context可以把结果写出
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        // 把map阶段写出的值累加起来，并且结合key，写出
        int sum = 0;
        int count = 0;
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()) {
            // 等同于下面的遍历效果
            IntWritable value = iterator.next();
            sum += value.get();
            count++;
        }
        result.set(sum);
        System.out.println("reduce funtion----key: " + key.toString() +
                ",value:" + result.get() + ",count:" + count);
        context.write(key, result);
    }
}
